package com.tencent.wxcloudrun.service.impl;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.tencent.wxcloudrun.dao.KUserMapper;
import com.tencent.wxcloudrun.model.KUser;
import com.tencent.wxcloudrun.service.KUserService;
import com.tencent.wxcloudrun.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author yuyongkang
 * @Date 2025/9/18 17:12
 */
@Service
@Slf4j
public class KUserServiceImpl implements KUserService {

    @Resource
    private KUserMapper kUserMapper;

    //机器码
    public static final Long MACHINE_ID = Long.valueOf(new Random().nextInt(9) + 1);


    @Override
    public void createOrUpdateUser(String openid) {
        log.info("更新用户信息");
        KUser select = new KUser();
        select.setOpenid(openid);
        List<KUser> kUsers = kUserMapper.selectUser(select);
        if (kUsers.size() == 0) {
            KUser kUser = new KUser();
            kUser.setId(SnowFlakeUtil.getInstance(MACHINE_ID).nextId());
            kUser.setOpenid(openid);
            kUser.setNickname("");
            kUser.setAvatarUrl("");
            kUser.setTotalKpoints(0);
            kUser.setCreateTime(new Date());
            kUserMapper.insertUser(kUser);
        } else {
            KUser kUser = kUsers.get(0);
            kUser.setOpenid(openid);
            kUserMapper.updateUser(kUser);
        }


    }

    @Override
    public List<KUser> selectUserListByOpenid(String openid) {
        KUser kUser = new KUser();
        kUser.setOpenid(openid);
        return kUserMapper.selectUser(kUser);
    }

    @Override
    public int updateUserInfo(KUser user) {
        return updateUserInfo(user);
    }
}
